package com.youngball.web.controller.sys.web;

import com.youngball.business.utill.Code;
import com.youngball.business.utill.ConstantClass;
import com.youngball.business.utill.DomainClubUtils;
import com.youngball.business.utill.ObjectNullUtils;
import com.youngball.shiro.dao.ShiroCacheRedisDao;
import com.youngball.shiro.entity.ChildResource;
import com.youngball.shiro.entity.User;
import com.youngball.shiro.entity.UserMenus;
import com.youngball.shiro.service.UserService;
import com.youngball.web.controller.BaseController;
import com.youngball.web.controller.sys.web.bind.annotation.CurrentUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**

 */
@Controller
@RequestMapping("${adminPath}/")
public class LoginController extends BaseController {

    @Autowired
    private UserService userService;

    @Resource(name="shiroCacheRedisDao")
    private ShiroCacheRedisDao shiroCacheRedisDao;

    @SuppressWarnings("Duplicates")
    @RequestMapping(value = "login",method = RequestMethod.GET)
    public ResponseEntity<Map> showLoginForm (HttpServletRequest req, HttpServletResponse response) {
        Map maps = new HashMap();
        Subject currentUser = SecurityUtils.getSubject();
        if (!currentUser.isAuthenticated()) {
            String error = "请先登录";
            maps.put("msg", error);
            maps.put("code", Code.NO_LOGIN.toString());
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.UNAUTHORIZED);
        } else {
            maps.put("code",6);
            maps.put("msg", "你已经登录");
            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
        }

    }
        @SuppressWarnings("Duplicates")
        @RequestMapping(value = "login",method = RequestMethod.POST,headers = "Accept=application/json")
        public ResponseEntity<Map> showLoginForm2 (HttpServletRequest req, HttpServletResponse response) {
            Map maps=new HashMap();

            String error = "";
              String exceptionClassName = (String)req.getAttribute("shiroLoginFailure");
            if(UnknownAccountException.class.getName().equals(exceptionClassName)) {
                error = "没找到帐号";
            } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
                error ="密码错误";
            }
            else if(LockedAccountException.class.getName().equals(exceptionClassName)) {
                error = "账号锁定";
            }
            else if(ExcessiveAttemptsException.class.getName().equals(exceptionClassName)) {
                error = "你输错的次数过多" ;
            }
            else if(AuthenticationException.class.getName().equals(exceptionClassName)) {
                error = "登陆验证失败，请检查您的用户名和密码！" ;
            }
            else {
                error="已经登录";
            }
            maps.put("msg",error);
            if ("已经登录".equals(error)){
                maps.put("code", Code.HAS_LOGIN.toString());
            }else {
                maps.put("code","1");
            }


            return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);

    }


    @SuppressWarnings("Duplicates")
    @RequestMapping(value = "logout2",method = {RequestMethod.GET})
  /*  @SystemControllerLog(description = "退出",code = "LOGOUT")*/
    public Object logout(HttpServletRequest req, HttpServletResponse response) {
        Map maps=new HashMap();
        DomainClubUtils.clearClubId();
        maps.put("msg","退出成功");
        maps.put("code","0");
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }

    @RequestMapping(value = "/kickoutUrl",method = {RequestMethod.GET})
    @ResponseBody
    public Object kickoutUrl(HttpServletRequest req, HttpServletResponse response) {
        Map maps=new HashMap();
        maps.put("msg","你的账号在其他地方登录");
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }

    @SuppressWarnings("Duplicates")
    @RequestMapping(value = "successUrl")
//    @SystemControllerLog(description = "登录",code = "LOGIN")
    public Object successUrl(@CurrentUser User loginUser, HttpServletRequest httpServletRequest) {
        UserMenus userMenus = new UserMenus();
        String aa=httpServletRequest.getSession().getId();
        String domainname=httpServletRequest.getHeader("domainname");
        httpServletRequest.getSession().setAttribute(aa,domainname+"&&"+DomainClubUtils.getClubId());
        Map maps=new HashMap();
        String name= loginUser.getUsername();
        User user= userService.findByMyUsername(name);

        if (user!=null) {
//            List<ChildResource> childResourceList = userService.findMenuPersion(user);
//            List<ConstantClass> persoins= userService.getBackPersion(user.getUsername());
//            userMenus=new UserMenus(childResourceList,user,persoins);
//            maps.put("data",userMenus);

            //若缓存中有,则取redis缓存中的值,
            userMenus = shiroCacheRedisDao.getLoginUser(user.getId());
            if (ObjectNullUtils.isNotBlank(userMenus)){
                maps.put("data",userMenus);
            }else {
                //若缓存中没有,则查询数据库,并且设置到redis中
                List<ChildResource> childResourceList = userService.findMenuPersion(user);
                List<ConstantClass> persoins = userService.getBackPersion(user.getUsername());
                userMenus = new UserMenus(childResourceList,user,persoins);
                shiroCacheRedisDao.setLoginUser(userMenus);
                maps.put("data",userMenus);
            }
        }
        maps.put("msg","登录成功");
        maps.put("time",new Date());
        maps.put("code", Code.SUC.toString());
        return new ResponseEntity<Map>(maps, responseHeaders, HttpStatus.OK);
    }
}
